package server.domaines.impl;

import java.awt.BorderLayout;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

import server.domaines.LocalDomaineManager;
import server.domaines.LocalDomaineManagerOperations;
import server.interfaces.Suscriber;
import server.topic.impl.TopicImpl;


public class LocalDomaineManagerImpl implements LocalDomaineManagerOperations{

	private Hashtable<String, TopicImpl> topics;
	
	JFrame frame = new JFrame();
	
	public LocalDomaineManagerImpl() {
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400, 400);
		frame.setLayout(new BorderLayout());
		frame.setVisible(true);
		
		topics = new Hashtable<String, TopicImpl>();
	}
	
	public void addTopic(TopicImpl topic){
		topic.setDomaine(this);
		topics.put(topic.getName(), topic);
		showFrame();
	}
	
	public void showFrame(){
		DefaultMutableTreeNode node = new DefaultMutableTreeNode("domain1");
		Set<String> keys = topics.keySet();
		Iterator<String> strings = keys.iterator();
		while(strings.hasNext()){
			String x = strings.next();
			DefaultMutableTreeNode node1 = topics.get(x).createNode();
			node.add(node1);
		}
		JTree tree = new JTree(node);
		JPanel panel = (JPanel)frame.getContentPane();
		if(panel.getComponentCount() != 0)
			panel.remove(panel.getComponentCount() - 1);
		panel.setLayout(new BorderLayout());
		panel.invalidate();
		panel.add(tree);
		panel.validate();
		panel.repaint();
	}
	
	@Override
	public Suscriber[] getTopicsSuscribers(String topicName, LocalDomaineManager sender) {
		int x = topicName.indexOf(".");
		if(x < 0){
			TopicImpl topic = topics.get(topicName);
			if(topic == null)
				return new Suscriber[]{null};
			return new Suscriber[]{topic.getSuscriber()};
		}
		String topicN = topicName.substring(0, x);
		TopicImpl topic = topics.get(topicN);
		if(topic == null)
			return new Suscriber[]{null};
		Suscriber suscriber = topic.getSuscriberWithPath(topicName.substring(x + 1, topicName.length()));
		if(suscriber == null)
			return new Suscriber[]{null};
		return new Suscriber[]{suscriber};
	}
}
